﻿using System;
using System.Drawing.Imaging;
using System.IO;
using System.Configuration;
using System.Threading;
using System.Net;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DemoPC
{
    class MyDemoPCWebClient:IDisposable
    {
        private string sessionId;
        private string pin;
        private string guid;
        private string baseUrl;
        private string uploadUrl;

        private WebClient client;
        bool enabled = true;
        bool stopped = true;
        // Track whether Dispose has been called.
        private bool disposed = false;
   
        public MyDemoPCWebClient(string sessionId, string guid)
        {
            this.guid = guid;
            this.sessionId = sessionId;
            this.Initialize();
            this.uploadUrl = this.baseUrl + "/remote/UploadDesktop/" + this.sessionId + "/" + this.guid;
        }

        public MyDemoPCWebClient()
        {
            this.guid = Guid.NewGuid().ToString();
            this.Initialize();

            string res = client.DownloadString(this.baseUrl + "/remote/session.jsp?guid=" + this.guid);
            try {
                string[] code = res.Split('/');
                this.sessionId = code[0];
                this.pin = code[1];
            } catch {
                throw new Exception("Invalid server response for session ID (" + res + "). ");
            }
            this.uploadUrl = this.baseUrl + "/remote/UploadDesktop/" + this.sessionId + "/" + this.guid;
        }

        private void Initialize()
        {
            this.client = new WebClient();
            this.client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0;)");
            this.baseUrl = ConfigurationManager.AppSettings["base.url"];
            if (string.IsNullOrEmpty(this.baseUrl))
            {
                this.baseUrl = "http://www.mydemopc.com";
            }
        }

        public void Dispose()
        {
            this.Dispose(true);

            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    this.endSession();
                    this.enabled = false;
                    this.client.Dispose();
                    this.client = null;
                }
                disposed = true;
            }
        }

        public bool Enabled 
        {
            get { return this.enabled; }
            set { this.enabled = value; }
        }

        public bool Stopped
        {
            get { return this.stopped; }
        }

        public string SessionId
        {
            get { return this.sessionId;}
        }

        public string SessionPin
        {
            get { return this.pin; }
        }

        public string MyPCGuid
        {
            get { return this.guid; }
        }

        public string BaseUrl
        {
            get { return this.baseUrl; }
        }

        public void endSession()
        {
            try
            {
                this.client.QueryString.Remove("session");
                this.client.QueryString.Add("session", this.sessionId);
                this.client.QueryString.Remove("guid");
                this.client.QueryString.Add("guid", this.guid);
                string s = this.client.DownloadString(this.baseUrl + "/remote/endScreenSession.jsp"); 
            }
            catch { 
            }
        }

        public void postScreen()
        {

            string tmp = Path.GetTempPath() + "screen.jpg";

            ScreenCapture ss = new ScreenCapture();
            try
            {
                for (int i = 0; i < 900 && this.enabled; i++)
                {
                    this.stopped = false;
                    using (Image img = ss.CaptureScreen())
                    {
                        img.Save(tmp, ImageFormat.Jpeg);
                    }
                    this.client.QueryString.Remove("session");
                    this.client.QueryString.Add("session", this.sessionId);
                    this.client.UploadFile(uploadUrl, "POST", tmp);
                    if (this.enabled)
                    {
                        Thread.Sleep(6 * 1000);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch {
            }

//            MessageBox.Show("Your desktop sharing session finished. Please exit.");

            this.stopped = true;
        }
    }
}
